/*
 * Copyright (c) 2012-2013, Yunnan Yuan Xin technology Co., Ltd.
 * 
 * All rights reserved.
 */
package net.jeeshop.web.action.phone;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.jeeshop.core.Services;
import net.jeeshop.core.dao.page.PagerModel;
import net.jeeshop.services.front.catalog.CatalogService;
import net.jeeshop.services.front.catalog.bean.Catalog;
import net.jeeshop.services.front.product.ProductService;
import net.jeeshop.services.front.product.bean.Product;
import net.jeeshop.services.front.serchHistory.SerchHistoryService;
import net.jeeshop.services.front.serchHistory.bean.SerchHistory;
import net.jeeshop.web.action.front.FrontBaseController;
import net.jeeshop.web.util.LoginUserHolder;
import net.jeeshop.web.util.RequestHolder;

/**
 * Hello控制器。
 * 
 */
@Controller
@RequestMapping(value = "/phone/search")
public class SearchController extends FrontBaseController<Product> {

	private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(SearchController.class);
	private static final String page_toIndex = "/phone/search/index";
	private static final String noResultPage = "/phone/search/noResult";
	private static final String productListPage = "/phone/search/productList";
	@Autowired
	private SerchHistoryService  serchHistoryService;
	@Autowired
	private ProductService productService;//商品服务
	
	@Resource
	private CatalogService catalogService;
	
    @RequestMapping(value = "", method = { RequestMethod.GET, RequestMethod.POST })
    public String search(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
    	
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("pageName", "商城搜索主页");
        return "";
    }
    @RequestMapping(value = "/getsearchList", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Object getsearchList(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
    	
        String key = request.getParameter("key").trim();
        List<String> serchList = new ArrayList<String>();
        Map jsObject = new HashMap<>();
        int resultCont = 0;
        Product ee = new Product();
        if(key != null && StringUtils.isNotEmpty(key)){
        	ee.setName(key);
            ee.setTop(20);//默认取20条
            List<Product> selectProductList = productService.selectList(ee);
            serchList.add(0, key);
            if(selectProductList != null && !selectProductList.isEmpty()){
            	resultCont = selectProductList.size();
            	for(Product ao : selectProductList){
            		serchList.add(ao.getName());
            	}
            }
        	
        }
        jsObject.put("status", "true");
        jsObject.put("count", resultCont);
        /***
        User user = (User)RequestHolder.getSession().getAttribute(ManageContainer.manage_session_user_info);
        //获取当前登录用户的搜索记录,若未登录不获取登录信息
        if(user != null && user.getId() != null && StringUtils.isNotBlank(user.getId())){
        	 SerchHistory e = new SerchHistory();
             e.setOffset(0);//从0开始取
             e.setPageSize(20);//默认取20条数据
             e.setUid(user.getId());//只获取当前用户数据
             if(StringUtils.isNotBlank(key)){
            	e.setContent(key); 
             }
             String[] strArr = {};
              serchList = serchHistoryService.selectList(e);
             model.addAttribute("serchList", serchList);
             jsObject.put("status", "true");
        }else{
        	model.addAttribute("serchList", new ArrayList());
        	jsObject.put("status", "false");
        }
       **/
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("pageName", "搜索结果");
        
        jsObject.put("data", serchList);
        
        return jsObject;
    }
    
    @RequestMapping(value = "/result", method = { RequestMethod.GET, RequestMethod.POST })
    public String result(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	response.setHeader("Access-Control-Allow-Origin", "*");
    	response.setContentType("text/html;charset=utf-8"); 
    	
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        
        //将当前运用名称传到前端
        model.addAttribute("appId", "seller");
        model.addAttribute("pageName", "商城搜索结果");
        return "";
    }
    
    /**点击搜索按钮时，判断用户如果登录，往搜索历史表中增加或更新记录
     * @param String counten 搜索内容
     * @param String uid 用户ID
     * 
     * **/
    @RequestMapping(value = "/addOrUpdtae", method = { RequestMethod.GET, RequestMethod.POST })
    public String add(HttpServletRequest request, HttpServletResponse response, HttpSession session,String key){
    	String serchContent = request.getParameter("key");
    	if(StringUtils.isNotBlank(key)){
    		serchContent = key;
    	}
    	String uid = "";
    	uid = getUserInfo();
    	
    	if( StringUtils.isNotBlank(uid) && StringUtils.isNotBlank(serchContent)){
    		//先根据用户ID和内容查找，是否已经有相同的历史记录
    		SerchHistory e = new SerchHistory();
    		e.setUid(uid);
    		e.setContent(serchContent);
    		SerchHistory ao = serchHistoryService.selectOne(e);
    		int count = 0;
    		if(ao != null && StringUtils.isNotBlank(ao.getId())){
    			e.setId(ao.getId());
    			e.setCount(ao.getCount() + 1);
    			serchHistoryService.update(e);
    		}else{
    			e.setCount(1);
    			serchHistoryService.insert(e);
    		}
    	}
    	return "true";
    }
    /**
     * 清除当前登录用户的检索信息
     * **/
    @RequestMapping(value = "/clear", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public String clear(HttpServletRequest request, HttpServletResponse response, HttpSession session){
    	String uid = "";
    	uid = getUserInfo();
    	String serchContent = request.getParameter("serchContent");
    	//根据用户Uid 清除用户搜索信息
    	if( StringUtils.isNotBlank(uid)){
    		SerchHistory e = new SerchHistory();
    		e.setUid(uid);
    		//结合当前登录用户  以及检索内容 删除指定信息
    		if(StringUtils.isNotBlank(serchContent)){
    			e.setContent(serchContent);
    		}
    		serchHistoryService.delete(e);
    	}
    	return "true";
    }
    /**
     * 点击搜索按钮时 检索商品库
     * @param String
     * **/
    @RequestMapping(value = "/go", method = { RequestMethod.GET, RequestMethod.POST })
    public String SerchGoods(Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session)  throws Exception{
    	String key = RequestHolder.getRequest().getParameter("key");//搜索关键字
    	String key1 = RequestHolder.getRequest().getParameter("key1");
    	String key2 = RequestHolder.getRequest().getParameter("key2");
    	String key3 = RequestHolder.getRequest().getParameter("key3");
    	
    	Product e = new Product();
		if(StringUtils.isNotBlank(key)){
			key = java.net.URLDecoder.decode(key,"UTF-8"); 
			e.setName(key);
		}
		if(StringUtils.isNotBlank(key3)){
			Catalog ca = new Catalog();
			ca.setId(key3);
			ca = catalogService.selectOne(ca);
			if(ca != null && StringUtils.isNotBlank(ca.getName())){
				e.setCbs(ca.getName());
			}
			
		}
		if(StringUtils.isNotBlank(key1) && StringUtils.isBlank(key2)){
			e.setCatalogID(key1);
			Catalog c = new Catalog();
			c.setPid(key1);
			List<Integer> queryCataLogs = new ArrayList<Integer>();
			List<Catalog> cataLogList = catalogService.selectList(c);
			if(cataLogList != null && cataLogList.size() >0){
				for(Catalog cc :cataLogList){
					queryCataLogs.add(Integer.valueOf(cc.getId()));
				}
			}
			queryCataLogs.add(Integer.valueOf(key1));
			e.setQueryCatalogIDs(queryCataLogs);
		}
		if(StringUtils.isNotBlank(key1) && StringUtils.isNotBlank(key2)){
			e.setCatalogID(key2);
			List<Integer> queryCataLogs = new ArrayList<Integer>();
			queryCataLogs.add(Integer.valueOf(key2));
			e.setQueryCatalogIDs(queryCataLogs);
		}
		
		List<List<Product>> resProduct = new ArrayList<List<Product>>();
		PagerModel pager = selectProductList0(e);
		List<Product> productList = productService.selectList(e);
		resProduct = convert(productList,2);
		model.addAttribute("productList", resProduct);
		model.addAttribute("pager", pager);
		model.addAttribute("key", key);
		e.clear();
		//搜索成功，向搜索记录表中增加或更新数据
		add( request, response, session,key);
		retrieval(model,key1);
		return page_toIndex;
    }
    /**
     * 搜索结果-检索
     * 获取所有分类，父类和子类
     * 
     * **/
    public void retrieval(Model model,String id){
    	//获取分类一
    	Catalog e = new Catalog();
    	e.setId(id);
    	List<Catalog> rootList = new ArrayList<Catalog>();
    	List<Catalog> childrenList = new ArrayList<Catalog>();
    	List<Catalog> catalogList = catalogService.selectList(e);
    	for(Catalog ao : catalogList){
    		if("0".equals(ao.getPid())){
    			rootList.add(ao);
    		}
    	}
    	//查询二级分类
    	e.clear();
		e.setPid(id);
		childrenList = catalogService.selectList(e);
    	//获取出版社信息
    	e.clear();
    	e.setType("ss");
    	e.setPid("0");
    	e.setShowInNav("y");
    	List<Catalog> catalogCbsList = catalogService.selectList(e);
    	
    	model.addAttribute("rootList", rootList);
    	model.addAttribute("childrenList", childrenList);
    	model.addAttribute("catalogCbsList", catalogCbsList);

    }
    
    /**
	 * 分页加载产品列表，每4个一行的显示
	 * @param e
	 * @return
	 * @throws Exception
	 */
	private PagerModel selectProductList0(Product e) throws Exception {
//		getE().setStatus(2);//加载已经上架的商品
//		getE().setOrderBy(orderBy);//设置排序规则
		PagerModel pager = super.selectPageList(getService(), e);//分页搜索数据库中的商品
//		doImage(result);
		return pager;
//		return convert4(result);
	}

	/**
	 * 产品集合转换为页面可以显示的数据结构，N个产品显示一行
	 * 具体一行显示几个 可以自己定义
	 * @return
	 */
	private List<List<Product>> convert(List<Product> result,int rowSize){
		if(result==null || result.size()==0){
			return null;
		}
		List<List<Product>> list = new LinkedList<List<Product>>();
		int nn = 0;
		int maxLen = rowSize;
		List<Product> row = new LinkedList<Product>();
		for(int i=0;i<result.size();i++){
			Product ee = result.get(i);
			row.add(ee);
			/*nn++;
			if(nn==maxLen){
				list.add(row);
				nn=0;
				row = new LinkedList<Product>();
			}
			
			if(result.size()==i+1){
				if(row.size()==0){
					row.add(ee);
				}
				list.add(row);
			}*/
			
		}
		list.add(row);
		return list;
	}
	
	@Override
	public Services<Product> getService() {
		return productService;
	}
	
	/**
     * 频繁用到当前用户信息 提出公用方法 判断用户是否已经登录
     * */
    public String getUserInfo(){
    	net.jeeshop.services.front.account.bean.Account aa =  LoginUserHolder.getLoginAccount();
    	String str = "";
    	if(aa != null && StringUtils.isNotBlank(aa.getId())){
    		str = aa.getId();
    	}
    	return str;
    }
	
    /**
     * 查询二级分类
     * @param catalogId
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/getSecondClassByPid", method = { RequestMethod.GET, RequestMethod.POST })
    public void getSecondClassByPid(Model model,HttpServletRequest request,HttpServletResponse response) {
    	Map jsonObject = new HashMap<>();
    	String catalogId = request.getParameter("catalogId");
    	jsonObject.put("succeed", false);
    	jsonObject.put("code", -1);
    	jsonObject.put("data", null);
    	if(StringUtils.isNotBlank(catalogId)) {
    		Catalog catalog = new Catalog();
    		catalog.setPid(catalogId);
    		List<Catalog> list = catalogService.selectList(catalog);
    		if(null != list && !list.isEmpty() && list.size() > 0) {
    			jsonObject.put("succeed", true);
    			jsonObject.put("data", list);
    			jsonObject.put("code", 0);
    		}
    	}
    	PrintWriter out = null;
    	try {
			out = response.getWriter();
			out.write(jsonObject.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			LOG.info("异常信息：%s",e);
			e.printStackTrace();
		} finally {
			if(null != out) {
				out.close();
			}
		}
    }
    
    @RequestMapping(value = "/filter", method = { RequestMethod.GET, RequestMethod.POST })
    public void filter(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception {
    	String key = RequestHolder.getRequest().getParameter("key");//搜索关键字
    	String key1 = RequestHolder.getRequest().getParameter("key1");
    	String key2 = RequestHolder.getRequest().getParameter("key2");
    	String key3 = RequestHolder.getRequest().getParameter("key3");
    	
    	Product e = new Product();
		if(StringUtils.isNotBlank(key)){
			key = java.net.URLDecoder.decode(key,"UTF-8"); 
			e.setName(key);
		}
		if(StringUtils.isNotBlank(key3)){
			Catalog ca = new Catalog();
			ca.setId(key3);
			ca = catalogService.selectOne(ca);
			if(ca != null && StringUtils.isNotBlank(ca.getName())){
				e.setCbs(ca.getName());
			}
			
		}
		if(StringUtils.isNotBlank(key1) && StringUtils.isBlank(key2)){
			e.setCatalogID(key1);
			Catalog c = new Catalog();
			c.setPid(key1);
			List<Integer> queryCataLogs = new ArrayList<Integer>();
			List<Catalog> cataLogList = catalogService.selectList(c);
			if(cataLogList != null && cataLogList.size() >0){
				for(Catalog cc :cataLogList){
					queryCataLogs.add(Integer.valueOf(cc.getId()));
				}
			}
			queryCataLogs.add(Integer.valueOf(key1));
			e.setQueryCatalogIDs(queryCataLogs);
		}
		if(StringUtils.isNotBlank(key1) && StringUtils.isNotBlank(key2)){
			e.setCatalogID(key2);
			List<Integer> queryCataLogs = new ArrayList<Integer>();
			queryCataLogs.add(Integer.valueOf(key2));
			e.setQueryCatalogIDs(queryCataLogs);
		}
		List<Product> productList = productService.selectList(e);
		Map jsonObject = new HashMap<>();
		jsonObject.put("succeed", true);
    	jsonObject.put("code", 0);
    	List<Product> sellList = productList;
    	sortList(productList, "getNowPrice", "asc");
    	sortList(sellList, "getSellcount", "desc");
    	jsonObject.put("priceList", productList);
    	jsonObject.put("sellList", sellList);
    	PrintWriter out = null;
    	try {
    		out = response.getWriter();
    		out.write(jsonObject.toString());
    	} catch(IOException ex) {
    		ex.printStackTrace();
    	} finally {
    		if(null != out) {
    			out.close();
    		}
    	}
    }
    
    /**
     * 排序
     * @param list
     * @param method
     * @param soft
     */
	@SuppressWarnings("unchecked")
	public void sortList(List list, final String method, final String soft) {
		Collections.sort(list, new Comparator() {
			@Override
			public int compare(Object a, Object b) {
				// TODO Auto-generated method stub
				int ret = 0;
				// 获取a 的方法名
				try {
					Method ma = a.getClass().getMethod(method, null);
					Method mb = b.getClass().getMethod(method, null);
					if (soft != null && "desc".equals(soft)) {
						ret = mb.invoke(((Object) b), null).toString().compareTo(ma.invoke(((Object) a), null).toString());
					} else {
						ret = ma.invoke(((Object) a), null).toString().compareTo(mb.invoke(((Object) b), null).toString());
					}
				} catch (NoSuchMethodException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return ret;
			}
		});
	}
	
	/**
	 * 加载搜素商品列表
	 * **/
	 @RequestMapping(value = "/serchProduct", method = { RequestMethod.GET, RequestMethod.POST })
	    @ResponseBody
	    public Object serchProduct(Model model,HttpServletRequest request, HttpServletResponse response, HttpSession session){
		 String valStr = request.getParameter("val").trim();
		 Product ee = new Product();
		 List<String> serchList = new ArrayList<String>();
		 StringBuilder resStr = new StringBuilder();
		 resStr.append("<ul>");
		 //根据检索值搜素商品信息
		 if(valStr != null && StringUtils.isNotEmpty(valStr)){
			 serchList.add(0, valStr);
	        	ee.setName(valStr);
	            List<Product> selectProductList = productService.selectList(ee);
	            if(selectProductList != null && !selectProductList.isEmpty()){
	            	for(Product ao : selectProductList){
	            		serchList.add(ao.getName());
	            	}
	            }
	        	
	        }
		 return serchList;
	 }
}
